<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="com.houduan.model.Session" %>
<%@ page import="com.houduan.model.Computer" %>
<%@ page import="java.util.List" %>
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>上机管理 - 网吧管理系统</title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/materialdesignicons.min.css" rel="stylesheet">
  <link href="css/style.min.css" rel="stylesheet">
</head>
<body>
<div class="lyear-layout-web">
  <div class="lyear-layout-container">
    <!-- 左侧导航栏 -->
    <aside class="lyear-layout-sidebar">
      <div id="logo" class="sidebar-header">
        <a href="index.jsp"><img src="images/logo-sidebar.png" alt="网吧管理系统" /></a>
      </div>
      <div class="lyear-layout-sidebar-scroll">
        <nav class="sidebar-main">
          <ul class="nav nav-drawer">
            <li class="nav-item"><a href="StatisticsServlet"><i class="mdi mdi-home"></i> 后台首页</a></li>
            <li class="nav-item"><a href="ComputerServlet?action=list"><i class="mdi mdi-laptop"></i> 电脑管理</a></li>
            <li class="nav-item"><a href="OrderServlet?action=list"><i class="mdi mdi-cart"></i> 订单管理</a></li>
            <li class="nav-item active"><a href="SessionServlet?action=list"><i class="mdi mdi-timer"></i> 上机管理</a></li>
            <li class="nav-item"><a href="UserServlet?action=list"><i class="mdi mdi-account"></i> 用户管理</a></li>
          </ul>
        </nav>
      </div>
    </aside>

    <header class="lyear-layout-header">
      <nav class="navbar navbar-default">
        <div class="topbar">
          <div class="topbar-left">
            <div class="lyear-aside-toggler">
              <span class="lyear-toggler-bar"></span>
              <span class="lyear-toggler-bar"></span>
              <span class="lyear-toggler-bar"></span>
            </div>
            <span class="navbar-page-title">网吧管理系统</span>
          </div>
          <ul class="topbar-right">
            <li class="dropdown dropdown-profile">
              <a href="javascript:void(0)" data-toggle="dropdown">
                <img class="img-avatar img-avatar-48 m-r-10" src="images/users/avatar.jpg" alt="用户头像" />
                <span>管理员 <span class="caret"></span></span>
              </a>
              <ul class="dropdown-menu dropdown-menu-right">
                <li><a href="change_password.jsp"><i class="mdi mdi-lock-outline"></i> 修改密码</a></li>
                <li><a href="logout.jsp"><i class="mdi mdi-logout-variant"></i> 退出登录</a></li>
              </ul>
            </li>
          </ul>
        </div>
      </nav>
    </header>
    <!-- 页面主要内容 -->
    <main class="lyear-layout-content">
      <div class="container-fluid">
        <h2>上机管理</h2>

        <!-- 按型号筛选空闲电脑 -->
        <div class="mb-4">
          <h4>筛选空闲电脑</h4>
          <form method="get" action="SessionServlet">
            <input type="hidden" name="action" value="filterByType">
            <div class="form-group">
              <label for="computerType">电脑型号</label>
              <select class="form-control" id="computerType" name="type">
                <option value="">-- 选择型号 --</option>
                <%
                  List<String> computerTypes = (List<String>) request.getAttribute("computerTypes");
                  if (computerTypes != null) {
                    for (String type : computerTypes) {
                %>
                <option value="<%= type %>"><%= type %></option>
                <%
                    }
                  }
                %>
              </select>
            </div>
            <button type="submit" class="btn btn-info">筛选</button>
          </form>
        </div>

        <!-- 当前空闲电脑列表 -->
        <div class="mb-4">
          <h4>当前空闲电脑</h4>
          <table class="table table-striped">
            <thead>
            <tr>
              <th>ID</th>
              <th>名称</th>
              <th>型号</th>
              <th>价格（每小时）</th>
              <th>状态</th>
            </tr>
            </thead>
            <tbody>
            <%
              List<Computer> freeComputers = (List<Computer>) request.getAttribute("freeComputers");
              if (freeComputers != null && !freeComputers.isEmpty()) {
                for (Computer computer : freeComputers) {
            %>
            <tr>
              <td><%= computer.getId() %></td>
              <td><%= computer.getName() %></td>
              <td><%= computer.getType() %></td>
              <td><%= computer.getPrice() %></td>
              <td><%= computer.getStatus() %></td>
            </tr>
            <%
              }
            } else {
            %>
            <tr>
              <td colspan="5" class="text-center">暂无空闲电脑</td>
            </tr>
            <% } %>
            </tbody>
          </table>
        </div>

        <!-- 上机操作 -->
        <!-- 上机操作 -->
        <div class="mb-4">
          <h4>上机操作</h4>
          <form method="post" action="SessionServlet?action=start">
            <div class="form-group">
              <label for="userId">用户 ID</label>
              <input type="number" class="form-control" id="userId" name="userId" required>
            </div>
            <div class="form-group">
              <label for="computerId">电脑 ID</label>
              <input type="number" class="form-control" id="computerId" name="computerId" required>
            </div>
            <div class="form-group">
              <label for="duration">上机时长（分钟）</label>
              <input type="number" class="form-control" id="duration" name="duration" required>
            </div>
            <button type="submit" class="btn btn-primary">开始上机</button>
          </form>
        </div>

        <!-- 提前下机操作 -->
        <div class="mb-4">
          <h4>提前下机操作</h4>
          <form method="post" action="SessionServlet?action=end">
            <div class="form-group">
              <label for="sessionId">上机记录 ID</label>
              <input type="number" class="form-control" id="sessionId" name="sessionId" required>
            </div>
            <button type="submit" class="btn btn-warning">提前下机</button>
          </form>
        </div>

        <!-- 上机记录 -->
        <div>
          <h4>上机记录</h4>
          <!-- 刷新按钮 -->
          <div class="mt-3 text-left">
            <a href="SessionServlet?action=list" class="btn btn-secondary">刷新</a>
          </div>
          <table class="table table-striped">
            <thead>
            <tr>
              <th>记录编号</th>
              <th>用户</th>
              <th>电脑</th>
              <th>开始时间</th>
              <th>结束时间</th>
              <th>时长（小时）</th>
              <th>费用</th>
            </tr>
            </thead>
            <tbody>
            <%
              List<Session> sessions = (List<Session>) request.getAttribute("sessions");
              if (sessions != null && !sessions.isEmpty()) {
                for (Session userSession : sessions) {
            %>
            <tr>
              <td><%= userSession.getId() %></td>
              <td><%= userSession.getUser() != null ? userSession.getUser().getUsername() : "未知用户" %></td>
              <td><%= userSession.getComputer() != null ? userSession.getComputer().getName() : "未知电脑" %></td>
              <td><%= userSession.getStartTime() != null ? userSession.getStartTime() : "未记录" %></td>
              <td><%= userSession.getEndTime() != null ? userSession.getEndTime() : "进行中" %></td>
              <td><%= String.format("%.2f", userSession.getDuration()) %></td> <!-- 显示时长 -->
              <td><%= String.format("%.2f", userSession.getCost()) %></td> <!-- 显示费用 -->
            </tr>
            <%
              }
            } else {
            %>
            <tr>
              <td colspan="7" class="text-center">暂无上机记录</td>
            </tr>
            <%
              }
            %>
            </tbody>

          </table>
        </div>

      </div>
    </main>
  </div>
</div>
<script>
  function updateSessionDetails() {
    // 获取当前时间
    const now = Date.now();

    // 遍历所有动态时长和费用
    document.querySelectorAll('td[id^="duration-"]').forEach(durationCell => {
      const sessionId = durationCell.id.split('-')[1];
      const startTime = parseInt(durationCell.getAttribute('data-start-time'));
      const endTime = durationCell.getAttribute('data-end-time');
      const costCell = document.querySelector(`#cost-${sessionId}`);
      const price = parseFloat(costCell.getAttribute('data-price'));

      // 计算时长（小时）
      const endMillis = endTime ? parseInt(endTime) : now;
      const duration = (endMillis - startTime) / (1000 * 60 * 60);
      durationCell.innerText = duration.toFixed(2);

      // 计算费用
      const cost = duration * price;
      costCell.innerText = cost.toFixed(2);
    });
  }

  // 页面加载时立即更新
  updateSessionDetails();

  // 每分钟更新一次
  setInterval(updateSessionDetails, 60000);
</script>

</body>
</html>
